import sys
from PyQt4 import QtCore

class PluginSettings:
	def __init__(self, settingsPath, pluginName):
		self.settings = QtCore.QSettings(settingsPath, QtCore.QSettings.IniFormat)
		self.pluginName = pluginName
		self.loadSettings()

	def loadSettings(self):
		self.settingsDict = None
		
		if self.settings == None or self.pluginName == None:
			print "settings obj or plugin name is None, returning"
			return

		self.settingsDict = dict()

		self.settings.beginGroup(self.pluginName)
		childKeys = self.settings.childKeys()

		for childKey in childKeys:
			self.settingsDict[unicode(childKey)] = self.settings.value(childKey)
		
		self.settings.endGroup()

	def getSetting(self, settingName):
		if self.settingsDict is None:
			print "settingsDic is None"
			return None

		settingValue = self.settingsDict.get(settingName)

		return settingValue

class Plugin:
	def __init__(self):
		self.pluginName = None
		self.pluginDescription = None
		self.pluginSettings = None

	def getPluginName(self):
		return self.pluginName

	def getPluginDescription(self):
		return self.pluginDescription

	def getConfigSettings(self):
		return None

	def loadPluginSettings(self, settingsPath):
		self.pluginSettings = PluginSettings(settingsPath, self.pluginName)
		self.pluginSettings.loadSettings()

	def getSetting(self, settingName):
		if not self.pluginSettings:
			return None

		return self.pluginSettings.getSetting(settingName)

	def processPluginOptions(self, argv):
		return True

	def makeStuffGoNow(self):
		return 0

	def runPlugin(self, argv=None):
		if not argv:
			argv = sys.argv
		
		if '--name' in argv:
			print self.getPluginName()
			return 0
		elif '--explain' in argv:
			print self.getPluginDescription()
			return 0
		elif '--lc' in argv:
			config = self.getConfigSettings()
			if type(config) == type(str()):
				print config
			elif type(config) == type(list()) or type(config) == type(tuple()):
				for item in self.getConfigSettings():
					print item
			else:
				return -1;
			return 0
		elif '--cf' in argv:
			cfIndex = argv.index('--cf') + 1

			if cfIndex >= len(argv):
				print 'Error: No config-file location was specified.'
				return -1

			print "loadPluginSettings"
			self.loadPluginSettings(argv[cfIndex])

			pluginOptions = None

			if (cfIndex + 1) < len(argv):
				pluginOptions = argv[cfIndex + 1:]

			if not self.processPluginOptions(pluginOptions):
				return -1

			print "makeStuffGoNow"
			return self.makeStuffGoNow()
		else:
			print 'ToDo: Plugin Usage...'
			return -1
        
